import React, { useState, useEffect } from 'react';
import { Tabs, Dropdown } from 'antd';
import { SyncOutlined } from '@ant-design/icons';
import { useLocation, useNavigate } from 'react-router-dom';
import './index.css'

const TabsView = ({ routes }) => {
  const [activeKey, setActiveKey] = useState('');
  const [panes, setPanes] = useState([{
    closable: false,
    key: "/Workbenches",
    title: "工作台"
  }]);
  const location = useLocation();
  const navigate = useNavigate();
 // 更新 localStorage
 const updateLocalStorage = (updatedPanes, updatedActiveKey) => {
    localStorage.setItem('tabsPanes', JSON.stringify(updatedPanes));
    localStorage.setItem('tabsActiveKey', updatedActiveKey);
  };
  // 根据路由匹配标签页标题
  const getTabTitle = (pathname) => {
    const findRoute = (routes, path) => {
        for (const route of routes) {
          // 检查当前路由是否匹配
          if (route.path === path) {
            return route;
          }
          // 如果有子路由，递归查找
          if (route.routes) {
            const subRoute = findRoute(route.routes, path);
            if (subRoute) {
              return subRoute;
            }
          }
        }
        return null; // 如果没有匹配的路由
      };
    
      const route = findRoute(routes, pathname);
      return route ? route.name : '未知页面';
  };

useEffect(() => {
    const savedPanes = JSON.parse(localStorage.getItem('tabsPanes'))
    const savedActiveKey = localStorage.getItem('tabsActiveKey')
    setPanes(savedPanes);
    setActiveKey(savedActiveKey);
    return () => {
      console.log('组件卸载');
    };
  }, []);

useEffect(() => {
    console.log("Panes updated:", panes);
    const { pathname } = location;
    updateLocalStorage(panes, pathname);
  }, [panes]);


  // 初始化和路由变化时更新标签页
  useEffect(() => {
    const { pathname } = location;
    addTab(pathname);
    setActiveKey(pathname);
  }, [location]);

  // 添加标签页
  const addTab = (pathname) => {
    const exist = panes.find(pane => pane.key === pathname);
    if (!exist) {
        const newPanes = [...panes, {
            title: getTabTitle(pathname),
            key: pathname,
            closable: pathname !== '/Workbenches' // 首页不可关闭
          }];
          setPanes(newPanes);
          console.log(panes);
          updateLocalStorage(newPanes, pathname);
    }
  };

  // 切换标签页
  const onChange = (key) => {
    setActiveKey(key);
    navigate(key);
    updateLocalStorage(panes, key);
  };

  // 关闭标签页
  const onEdit = (targetKey, action) => {
    if (action === 'remove') {
      const newPanes = panes.filter(pane => pane.key !== targetKey);
      console.log(newPanes);
      
      setPanes(newPanes);
      // 如果关闭的是当前页，则跳转到最后一个标签
      if (targetKey === activeKey) {
        const lastPane = newPanes[newPanes.length - 1];
        setActiveKey(lastPane.key);
        navigate(lastPane.key);
      }
      updateLocalStorage(newPanes, activeKey);
    }
  };

  // 刷新当前页面
  const refreshTab = () => {
    navigate(activeKey);
  };

  // 右键菜单选项
  const getDropdownItems = (pane) => {
    return {
      items: [
        {
          key: 'refresh',
          label: '刷新页面',
          icon: <SyncOutlined />,
          onClick: () => refreshTab()
        },
        {
          key: 'closeOthers',
          label: '关闭其他',
          onClick: () => {
            const newPanes = panes.filter(item => 
              item.key === pane.key || !item.closable
            );
            setPanes(newPanes);
            if (activeKey !== pane.key) {
              setActiveKey(pane.key);
              navigate(pane.key);
              updateLocalStorage(newPanes, pane.key);
            }
          }
        },
        {
          key: 'closeRight',
          label: '关闭右侧',
          onClick: () => {
            const index = panes.findIndex(item => item.key === pane.key);
            const newPanes = panes.filter((item, i) => 
              i <= index || !item.closable
            );
            setPanes(newPanes);
            if (!newPanes.find(item => item.key === activeKey)) {
              setActiveKey(pane.key);
              navigate(pane.key);
              updateLocalStorage(newPanes, pane.key);
            }
          }
        },
        {
          key: 'closeLeft',
          label: '关闭左侧',
          onClick: () => {
            const index = panes.findIndex(item => item.key === pane.key);
            const newPanes = panes.filter((item, i) => 
              i >= index || !item.closable
            );
            setPanes(newPanes);
            if (!newPanes.find(item => item.key === activeKey)) {
              setActiveKey(pane.key);
              navigate(pane.key);
              updateLocalStorage(newPanes, pane.key);
            }
          }
        }
      ]
    };
  };

  return (
    <Tabs
      hideAdd
      type="editable-card"
      activeKey={activeKey}
      onChange={onChange}
      onEdit={onEdit}
      className="custom-tabs"
      items={panes
        .filter(pane => pane.title && pane.title !== '未知页面')
        .map(pane => ({
        ...pane,
        label: (
          <Dropdown
            trigger={['contextMenu']}
            menu={getDropdownItems(pane)}
          >
            <span className="tab-label">{pane.title}</span>
          </Dropdown>
        )
      }))}
    />
  );
};

export default TabsView; 